import type { PageParam, PageResult } from '@vben/request';

import { requestClient } from '#/api/request';

export namespace CommentApi {
  /** 评论信息 */
  export interface Comment {
    content: string; // 评论内容
    createTime: string;
    id: number;
    images?: string[]; // 评论图片
    isLiked: boolean; // 当前用户是否已点赞
    likeCount: number; // 点赞数
    parentId?: number; // 父评论ID（回复时使用）
    rating: number; // 评分 (1-5)
    replies?: Comment[]; // 回复列表
    replyCount: number; // 回复数
    replyTo?: number; // 回复的评论ID
    replyToUser?: string; // 回复的用户名
    status: 'approved' | 'deleted' | 'pending' | 'rejected'; // 评论状态
    targetId: number; // 评论目标ID
    targetType: 'dress' | 'makeupartist' | 'package' | 'photographer'; // 评论目标类型
    updateTime: string;
    userAvatar?: string; // 用户头像
    userId: number; // 用户ID
    userName: string; // 用户名称
  }

  /** 评论统计 */
  export interface CommentStats {
    approvedCount: number; // 已通过评论数
    averageRating: number; // 平均评分
    ratingDistribution: {
      rating1Percent: number;
      rating2Percent: number;
      rating3Percent: number;
      rating4Percent: number;
      rating5Percent: number;
    };
    rating1Count: number; // 1星评论数
    rating2Count: number; // 2星评论数
    rating3Count: number; // 3星评论数
    rating4Count: number; // 4星评论数
    rating5Count: number; // 5星评论数
    recentComments?: Comment[]; // 最近评论
    targetId: number;
    targetType: string;
    totalCount: number; // 总评论数
    totalLikeCount: number; // 总点赞数
  }

  /** 评论查询参数 */
  export interface CommentQueryParams extends PageParam {
    content?: string;
    createTime?: string[];
    endTime?: string;
    keyword?: string;
    rating?: number;
    startTime?: string;
    status?: string;
    targetId?: number;
    targetType?: string;
    userId?: number;
    userName?: string;
  }
}

// ==================== 用户端接口（7个） ====================

/** 1. 创建评论 ⭐ */
export function createComment(data: {
  content: string;
  images?: string[];
  rating: number;
  targetId: number;
  targetType: 'dress' | 'makeupartist' | 'package' | 'photographer';
}) {
  return requestClient.post<number>('/wedding/comment/create', data);
}

/** 2. 更新评论（只能改自己的） */
export function updateComment(data: {
  content?: string;
  id: number;
  images?: string[];
  rating?: number;
}) {
  return requestClient.put<boolean>('/wedding/comment/update', data);
}

/** 3. 删除评论（只能删自己的） */
export function deleteComment(id: number) {
  return requestClient.delete<boolean>(`/wedding/comment/delete?id=${id}`);
}

/** 4. 回复评论 ⭐ */
export function replyComment(data: { content: string; parentId: number }) {
  return requestClient.post<number>('/wedding/comment/reply', data);
}

/** 5. 点赞评论 */
export function likeComment(commentId: number) {
  return requestClient.post<boolean>(
    `/wedding/comment/like?commentId=${commentId}`,
  );
}

/** 6. 取消点赞 */
export function unlikeComment(commentId: number) {
  return requestClient.post<boolean>(
    `/wedding/comment/unlike?commentId=${commentId}`,
  );
}

/** 7. 检查点赞状态 */
export function isLikedComment(commentId: number) {
  return requestClient.get<boolean>(
    `/wedding/comment/is-liked?commentId=${commentId}`,
  );
}

/** 点赞/取消点赞（自动判断，需要先查询点赞状态） */
export async function toggleLike(commentId: number) {
  // 先查询当前用户是否已点赞
  const isLiked = await isLikedComment(commentId);
  
  // 根据点赞状态调用对应接口
  if (isLiked) {
    return unlikeComment(commentId);
  } else {
    return likeComment(commentId);
  }
}

// ==================== 统计接口（2个） ====================

/** 8. 获取评论列表 ⭐ */
export function getTargetComments(
  targetType: string,
  targetId: number,
  params?: PageParam,
) {
  return requestClient.get<PageResult<CommentApi.Comment>>(
    '/wedding/comment/list-by-target',
    { params: { pageNo: 1, pageSize: 10, targetId, targetType, ...params } },
  );
}

/** 9. 获取评论统计 ⭐ */
export function getCommentStats(targetType: string, targetId: number) {
  return requestClient.get<CommentApi.CommentStats>(
    '/wedding/comment-stats/by-target',
    { params: { targetId, targetType } },
  );
}

// ==================== 管理端接口（4个） ====================

/** 10. 批量审核评论 */
export function batchApproveComments(
  ids: number[],
  status: 'approved' | 'rejected',
  remark?: string,
) {
  return requestClient.post<boolean>('/wedding/comment/approve', {
    ids,
    remark,
    status,
  });
}

/** 单个审核评论（调用批量接口） */
export function approveComment(
  id: number,
  status: 'approved' | 'rejected',
  remark?: string,
) {
  return batchApproveComments([id], status, remark);
}

/** 11. 批量删除评论 */
export function batchDeleteComments(ids: number[]) {
  return requestClient.delete<boolean>(
    `/wedding/comment/batch-delete?ids=${ids.join(',')}`,
  );
}

/** 12. 评论分页查询（管理后台） */
export function getCommentPage(params: CommentApi.CommentQueryParams) {
  return requestClient.get<PageResult<CommentApi.Comment>>(
    '/wedding/comment/page',
    { params },
  );
}

/** 获取评论详情 */
export function getComment(id: number) {
  return requestClient.get<CommentApi.Comment>(`/wedding/comment/get?id=${id}`);
}

/** 13. 导出评论 */
export function exportComments(params: CommentApi.CommentQueryParams) {
  return requestClient.download('/wedding/comment/export-excel', { params });
}

// ==================== 统计管理接口 ====================

/** 批量获取统计 */
export function getBatchCommentStats(targetType: string, targetIds: number[]) {
  return requestClient.get<Record<number, CommentApi.CommentStats>>(
    '/wedding/comment-stats/batch-by-targets',
    { params: { targetIds, targetType } },
  );
}

/** 重新计算统计 */
export function recalculateStats(targetType: string, targetId: number) {
  return requestClient.post<boolean>(
    '/wedding/comment-stats/recalculate',
    null,
    { params: { targetId, targetType } },
  );
}

// ==================== 其他接口 ====================

/** 举报评论 */
export function reportComment(commentId: number, reason: string) {
  return requestClient.post(`/wedding/comment/report/${commentId}`, {
    reason,
  });
}
